// @ts-nocheck
import { make }  from '../../utils/dom';
import { uniqueId } from '@/server-lib/tools';
import './form.css';

const formTypes =  [
  {label: '文本框', value: 'input'},
  {label: '单选框', value: 'radio'},
  {label: '复选框', value: 'checkbox'},
]

// export const initSchema = {
//   id: '',
//   mode: 'edit',
//   title: '表单标题 - 内测试版',
//   api: '',
//   config: [
//     {
//       type: 'input',
//       id: '1',
//       name: '姓名',
//       value: ''
//     },
//     {
//       type: 'radio',
//       name: '职业',
//       value: '',
//       id: '2',
//       options: [
//         {label: '工程师', value: '工程师'},
//         {label: '老板', value: '老板'},
//         {label: '设计师', value: '设计师'}
//       ]
//     },
//     {
//       type: 'checkbox',
//       name: '爱好',
//       id: '3',
//       value: '',
//       options: [
//         {label: '工程师', value: '工程师'},
//         {label: '老板', value: '老板'},
//         {label: '设计师', value: '设计师'}
//       ]
//     }
//   ]
// }

class FormRender {
    static get toolbox() {
      return {
        
      };
    }
  
    constructor(props = {}){
      // edit | readOnly
      this.mode = props.mode || 'edit';
      this.title = props.title || '';
      this.api = props.api;
      this.config = props.config || [];
      this.options = [
        {
          type: 'input',
          label: '文本框',
        },
        {
          type: 'radio',
          label: '单选框',
          options: ['选项一', '选项二', '选项三']
        },
        {
          type: 'checkbox',
          label: '复选框',
          options: ['选项一', '选项二', '选项三']
        }
      ];
      this.data = {};
      this.id = props.id;
      this.wrapper = null;
      this.onSave = props.onSave;
      this.onSubmit = props.onSubmit;
    }
  
    render(){
      const wrap = make('div', 'wep-es-from');
      if(this.mode === 'edit') {
        const title = this.createEditInput('title', '表单标题', this.title);
        const formItems = [];
        if(this.config.length) {
          for(let i=0; i < this.config.length; i++) {
            const item = this.config[i];
            if(item.type === 'input'){
              const input = this.createEditInput(item.id, item.name, item.name);
              formItems.push(input);
            }
            if(item.type === 'radio'){
              const value = item?.options?.map(v => v.label).join('-') || '';
              const radio = this.createEditOptions(item.id, item.name, value, item.type);
              formItems.push(radio);
            }
            if(item.type === 'checkbox'){
              const value = item?.options?.map(v => v.label).join('-') || '';
              const checkbox = this.createEditOptions(item.id, item.name, value, item.type);
              formItems.push(checkbox);
            }
          }
        }
        // 按钮组
        const footerBtnGroup = make('div', 'wep-es-formItem');
        const saveBtn = this.createButton('保存', () => {
          this.onSave({title: this.title, config: this.config});
        });
        const addBtn = this.createButton('添加', () => {
          wrap.insertBefore(this.addFormItem(), footerBtnGroup);
        });
        footerBtnGroup.append(addBtn, saveBtn);
        wrap.append(title, ...formItems, footerBtnGroup);
      }

      if(this.mode === 'readOnly') {
        const title = make('h3', 'wep-es-from-title', {innerText: this.title});
        const formItems = [];
        if(this.config.length) {
          for(let i=0; i < this.config.length; i++) {
            const item = this.config[i];
            if(item.type === 'input'){
              const input = this.createInput(item.id, item.name, item.value);
              formItems.push(input);
            }
            if(item.type === 'radio'){
              const radio = this.createRadio(item.id, item.name, item.options);
              formItems.push(radio);
            }
            if(item.type === 'checkbox'){
              const checkbox = this.createCheckbox(item.id, item.name, item.options);
              formItems.push(checkbox);
            }
          }
          const submitBtn = this.createButton('提交', () => {
            const form = [];
            this.config.forEach(v => {
              if(this.data[v.id] === undefined) {
                form.push({name: v.name, value: v.type === 'input' ? '' : []})
                return
              }
              form.push({name: v.name, value: this.data[v.id]['value']})
            })
            this.onSubmit(form);
          });
          wrap.append(title, ...formItems, submitBtn);
        }
      }
      return wrap
    }

    createEditInput(id: string, name: string, value: string, onDel: () => void) {
      const wrap = make('div', 'wep-es-formItem');
      const label = make('div', 'wep-es-label', { innerHTML: `${id === 'title' ? name : '字段名称'} : `, id });
      const ipt = make('input', 'wep-es-input', {placeholder: `请输入字段名称`, value});
      const delBtn = make('div', 'wep-es-btn', { innerHTML: `删除` });

      // 如果是title，隐藏删除按钮
      if(id === 'title') {
        wrap.append(label, ipt);
      }else {
        wrap.append(label, ipt, delBtn);
        delBtn.addEventListener('click', (event) => {
          wrap.remove();
          this.delConfigRow(id);
          onDel && onDel();
        }, false)
      }
      
      ipt.addEventListener('change', (event) => {
        if(id === 'title') {
          this.title = event.target.value;
          return
        }
        this.onConfigChange(id, 'input', name, event.target.value);
      }, false)

      return wrap
    }

    createEditOptions(id: string, name: string, value: string, type: string, onDel: () => void) {
      const wrap = make('div', 'wep-es-formItem');
      const label = make('div', 'wep-es-label', { innerHTML: `字段名称 : `, id });
      const ipt = make('input', 'wep-es-input', {placeholder: `请输入字段名称`, value: name});
      ipt.style.width = '10em';
      const optIpt = make('input', 'wep-es-input', {placeholder: `请输入选项数据，用 - 区分`, value});
      const delBtn = make('div', 'wep-es-btn', { innerHTML: `删除` });

      wrap.append(label, ipt, optIpt, delBtn);
      delBtn.addEventListener('click', (event) => {
        wrap.remove();
        this.delConfigRow(id);
        onDel && onDel();
      }, false)
      
      ipt.addEventListener('change', (event) => {
        this.onConfigChange(id, 'input', name, event.target.value, type);
      }, false)

      optIpt.addEventListener('change', (event) => {
        let optionValue = event.target.value.split('-').map(v => ({label: v, value: v}));
        this.onConfigChange(id, 'options', name, optionValue, type);
      }, false)

      return wrap
    }

    addFormItem() {
      const wrap = make('div', 'wep-es-addArea');
      let item = null;
      const typeOptions = this.createRadio(Date.now() + '', '表单类型', formTypes, (value) => {
        if(item) {
          item.remove();
        }
        const id = uniqueId();
        if(value === 'input') {
          item = this.createEditInput(id, '', '', () => {
            wrap.remove();
          });
        }
        if(value === 'radio' || value === 'checkbox') {
          item = this.createEditOptions(id, '', '', value, () => {
            wrap.remove();
          });
        }
        wrap.append(item);
      });
      wrap.append(typeOptions);
      return wrap
    }

    createInput(id: string, name: string, value: string) {
      const wrap = make('div', 'wep-es-formItem');
      const label = make('div', 'wep-es-label', { innerHTML: `${name} : `, id });
      const ipt = make('input', 'wep-es-input', {placeholder: `请输入${name}`, value});
      wrap.append(label, ipt);
      ipt.addEventListener('change', (event) => {
        this.onChange(id, 'input', name, event.target.value);
      }, false)
      return wrap
    }

    createRadio(id: string, name: string, options = [], cb: (value: string) => void) {
      const wrap = make('div', 'wep-es-formItem');
      const buttons = make('div', 'radio-buttons-container');
      const label = make('div', 'wep-es-label', { innerHTML: `${name} : `});
      wrap.append(label);
      for(let i=0; i < options.length; i++) {
        const sub_id = uniqueId();
        const item = options[i];
        const radioWrap = make('div', 'radio-button');
        const ipt = make('input', 'radio-button__input', { name: `radio-group_${id}`, id: `radio_${sub_id}`, type: 'radio', value: item.value });
        const label = make('label', 'radio-button__label', { htmlFor: `radio_${sub_id}`});
        const span = make('span', 'radio-button__custom');
        const text = make('span', '', { innerText: item.label});
        label.append(span, text);
        radioWrap.append(ipt, label);
        buttons.appendChild(radioWrap);
        ipt.addEventListener('change', (event) => {
          if(!cb) {
            this.onChange(id, 'radio', name, event.target.value);
            return
          }
          
          cb && cb(event.target.value);
        }, false)
      }
      wrap.append(buttons);
      return wrap
    }

    createCheckbox(id: string, name: string, options = []) {
      const wrap = make('div', 'wep-es-formItem');
      const checkbox = make('div', 'wep-es-checkbox');
      const label = make('div', 'wep-es-label', { innerHTML: `${name} : `});
      checkbox.append(label);
      wrap.append(checkbox);
      
      for(let i=0; i < options.length; i++) {
        const item = options[i];
        const checkboxWrap = make('label', 'checkbox-container');
        const ipt = make('input', '', { type: 'checkbox', value: item.value });
        const icon = make('span', 'checkmark');
        const label = make('span', 'label', {innerText: item.label});

        checkboxWrap.append(ipt, icon, label);
        wrap.appendChild(checkboxWrap);
        ipt.addEventListener('change', (event) => {
          this.onChange(id, 'checkbox', name, event.target.value);
        }, false)
      }
      return wrap
    }

    createButton(text: string, cb: () => void) {
      const wrap = make('div', 'wep-es-formItem');
      const btn = make('button', 'wep-es-submitBtn');
      const span = make('span', '', { innerText: text });
      btn.append(span);
      wrap.append(btn);
      btn.addEventListener('click', (event) => {
        cb && cb();
      }, false)
      return wrap
    }

    onChange(id, type, name, value) {
      if(type === 'checkbox') {
        if(this.data[id]) {
          const arr = this.data[id].value;
          if(arr.includes(value)) {
            this.data[id] = {
              id, type, name, value: arr.filter(v => v !== value)
            }
          }else {
            this.data[id] = {
              id, type, name, value: [...arr, value]
            }
          }
        }else {
          this.data[id] = {
            id, type, name, value: [value]
          }
        }
        return
      }

      if(type === 'radio') {
        this.data[id] = {
          id, type, name, value: [value]
        }
        return
      }

      this.data[id] = {
        id, type, name, value
      }
    }

    onConfigChange(id, type, name, value, specType) {
      const hasEl = this.config.find(v => v.id === id);
      if(!hasEl) {
        if(type === 'input') {
          this.config.push(
            {
              type: specType || type,
              name: value,
              id,
              value: '',
            }
          );
          return
        }

        if(type === 'options') {
          this.config.push( 
            {
              type: specType,
              name,
              id,
              value,
              options: value
            }
          );
          return
        } 
      }
      this.config = this.config.map(v => {
        if(v.id === id) {
          if(type === 'input') {
            return {
              ...v,
              // type: type,
              name: value
            }
          }else if(type === 'options') {
            return {
              ...v,
              type: specType,
              options: value
            }
          }
        }
        return v
      })
    }

    delConfigRow(id) {
      this.config = this.config.filter(v => v.id !== id);
    }
  }

export default FormRender